package demo1;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-08-04
 * Time: 8:54
 */
public class BubbleSort {

    /**
     * 冒泡排序
     * 时间复杂度 O(N^2)
     * 空间复杂 O(1)
     * 是一种稳定的排序, 但是稳定的前提是交换的条件 array[j] > array[j + 1] 没有等号
     *
     * @param array 排序数组
     */
    public static void bubbleSort(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            boolean flag = true;
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    swap(array, j, j + 1);
                    flag = false;
                }
            }
            if (flag) {
                break;
            }
        }
    }

    private static void swap(int[] array, int j, int i) {
        int tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }

    public static void main(String[] args) {
        int[] array = {3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48};

        BubbleSort.bubbleSort(array);
        System.out.println(Arrays.toString(array));
    }
}
